<template>
	<cl-page>
		<view class="shopping-cart-page">
			<!-- 自定义顶部栏 -->
			<view class="custom-header">
				<cl-status-bar />
				<view class="header-content">
					<text class="header-title">购物车</text>
					<view class="header-badge" v-if="spCart.list.length > 0">
						<text class="badge-text">{{ spCart.list.length }}</text>
					</view>
					<view class="header-action" v-if="!isEmpty(spCart.list)">
						<text
							class="action-text"
							@tap="op.command('delete-confirm')"
							v-if="op.mode == 'delete'"
						>
							完成
						</text>
						<text class="action-text" @tap="op.change('delete')" v-else> 管理 </text>
					</view>
				</view>
			</view>

			<!-- 内容区域 -->
			<view class="content-area">
				<!-- 促销横幅 -->
				<view v-if="spCart.activeFullReductions.length > 0" class="promotion-banner">
					<!-- 促销活动滑动卡片 -->
					<scroll-view scroll-x class="promotion-scroll" :show-scrollbar="false">
						<view class="promotion-container">
							<view
								v-for="reduction in spCart.activeFullReductions"
								:key="reduction.billNo"
								class="promotion-card"
								:class="{
									active:
										spCart.selectedTotalAmount >= getMinThreshold(reduction),
								}"
							>
								<view class="card-bg"></view>
								<view class="card-content">
									<view class="card-header">
										<view class="card-icon">
											<cl-icon name="ticket" color="#fff" size="24" />
										</view>
										<text class="card-title">{{ reduction.promName }}</text>
									</view>
									<view class="card-rules">
										<view
											v-for="(detail, idx) in reduction.details.slice(0, 3)"
											:key="detail.id"
											class="rule-item"
										>
											<text class="rule-condition">
												满{{ formatPrice(detail.taxAmount) }}
											</text>
											<text class="rule-discount">
												{{ Number(detail.dedRate) }}折
											</text>
										</view>
									</view>
									<view class="card-status">
										<view
											v-if="
												spCart.selectedTotalAmount >=
												getMinThreshold(reduction)
											"
											class="status-met"
										>
											<cl-icon name="check" size="12" color="#10b981" />
											<text>已满足</text>
										</view>
										<view v-else class="status-need">
											<text>
												还差{{
													formatPrice(
														getMinThreshold(reduction) -
															spCart.selectedTotalAmount
													)
												}}
											</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</scroll-view>

					<!-- 当前优惠提示 -->
					<view v-if="spCart.bestDiscount && user.token" class="discount-tip">
						<view class="tip-icon">
							<cl-icon name="el-icon-discount" size="20" color="#10b981" />
						</view>
						<text class="tip-text">
							已享{{ Number(spCart.bestDiscount.rate) }}折，省{{
								formatPrice(spCart.discountAmount)
							}}
						</text>
					</view>
				</view>

				<!-- 商品列表 -->
				<view class="cart-list" v-if="!isEmpty(spCart.list)">
					<view class="list-container">
						<!-- 商品分组（可按商家或类型分组） -->
						<view class="cart-group">
							<view
								v-for="(item, index) in spCart.list"
								:key="item.id"
								class="cart-item-wrapper"
								:class="{ 'last-item': index === spCart.list.length - 1 }"
							>
								<!-- 滑动删除容器 -->
								<view class="swipe-action">
									<cart-item
										:item="item"
										:show-checkbox="true"
										:edit-mode="op.mode === 'delete'"
										@delete="onDeleteItem"
										@quantity-change="onQuantityChange"
										class="modern-cart-item"
									/>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-else>
					<view class="empty-content">
						<view class="empty-icon">
							<cl-icon name="shopping-cart" size="120" color="#e0e0e0" />
						</view>
						<text class="empty-title">购物车还是空的</text>
						<text class="empty-desc">快去挑选心仪的商品吧</text>
						<cl-button
							type="primary"
							round
							size="large"
							@tap="router.push('/pages/goods/list')"
							class="go-shopping-btn"
						>
							<cl-icon name="search" :margin-right="8" />
							去逛逛
						</cl-button>
					</view>
				</view>
			</view>

			<!-- 底部结算栏 -->
			<view class="bottom-bar" v-if="!isEmpty(spCart.list)">
				<view class="bar-content">
					<view class="select-all">
						<cl-checkbox
							round
							:model-value="selectAll"
							@change="onSelectAllChange"
							class="custom-checkbox"
						>
							<text class="select-text">全选</text>
						</cl-checkbox>
					</view>

					<view class="price-info" v-if="op.mode == 'settle'">
						<view class="price-detail" v-if="user.token">
							<view v-if="spCart.bestDiscount" class="original-price">
								<text class="price-label">原价</text>
								<text class="price-value line-through">
									{{ formatUserPrice(spCart.selectedTotalAmount, user, 1) }}
								</text>
							</view>
							<view class="total-price">
								<text class="price-label">合计</text>
								<text class="price-value">
									{{
										formatUserPrice(
											spCart.finalPrice || spCart.selectedTotalAmount,
											user
										)
									}}
								</text>
							</view>
						</view>
						<view class="price-detail" v-else>
							<text class="login-tip">登录后查看价格</text>
						</view>
						<cl-button
							type="primary"
							round
							@tap="toSettle"
							class="settle-btn"
							:disabled="selectedCount === 0 || op.settling"
							:loading="op.settling"
						>
							{{ op.settling ? "结算中..." : "去结算" }}
							<text v-if="selectedCount > 0 && !op.settling" class="count-badge">
								({{ selectedCount }})
							</text>
						</cl-button>
					</view>

					<view class="delete-action" v-else-if="op.mode == 'delete'">
						<cl-button
							type="danger"
							round
							plain
							@tap="toDel()"
							class="delete-btn"
							:disabled="!spCart.list.some((e) => e.checked)"
						>
							<cl-icon name="delete" :margin-right="8" />
							删除选中
						</cl-button>
					</view>
				</view>
			</view>
		</view>

		<tabbar />
	</cl-page>
</template>

<script lang="ts" setup>
import { computed, reactive } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { useShoppingCart } from "/@/hooks";
import type { OrderGoods } from "/@/hooks/shopping-cart";
import { isEmpty } from "lodash-es";
import { useCool } from "/@/cool";
import { useUi } from "/$/cool-ui";
import { useStore } from "/@/cool/store";
import { formatUserPrice } from "/@/utils/price";
import CartItem from "/@/components/goods/cart-item.vue";
import Tabbar from "./components/tabbar.vue";

type OpMode = "settle" | "delete";

const { router } = useCool();
const spCart = useShoppingCart();
const ui = useUi();
const { user } = useStore();

// 页面显示时获取购物车数据
onShow(() => {
	spCart.fetchCartList();
	spCart.fetchFullReductions();
});

// 操作
const op = reactive({
	mode: "settle" as OpMode,
	settling: false, // 结算loading状态

	change(key: OpMode) {
		op.mode = key;
	},

	command(key: string) {
		switch (key) {
			case "delete-confirm":
				op.done();
				break;
		}
	},

	done() {
		op.mode = "settle";
	},
});

// 全选开关
const selectAll = computed(() => {
	return !isEmpty(spCart.list) && !spCart.list.find((e) => !e.checked);
});

// 选中商品数量
const selectedCount = computed(() => {
	return spCart.list.filter((e) => e.checked).length;
});

// 监听全选切换
function onSelectAllChange(val?: boolean) {
	spCart.list.forEach((e) => {
		e.checked = val;
	});
}

// 格式化价格
function formatPrice(price: number): string {
	return `¥${price.toFixed(2)}`;
}

// 获取满减促销的最小门槛
function getMinThreshold(reduction: any): number {
	if (reduction.details.length === 0) return 0;
	return Math.min(...reduction.details.map((detail: any) => Number(detail.taxAmount)));
}

// 删除单个商品
async function onDeleteItem(item: OrderGoods) {
	ui.showConfirm({
		title: "提示",
		message: "确定删除该商品吗？",
		async callback(action) {
			if (action == "confirm") {
				try {
					await spCart.del(item.id!);
					// 刷新购物车列表
					await spCart.fetchCartList();
					// 刷新满减活动
					await spCart.fetchFullReductions();
					ui.showToast("删除成功");
				} catch (error) {
					console.error("删除商品失败:", error);
					ui.showToast("删除失败");
				}
			}
		},
	});
}

// 数量变化处理
async function onQuantityChange(item: OrderGoods, count: number) {
	if (count == 0) {
		onDeleteItem(item);
		return;
	}

	// 验证中包装数量
	if (!spCart.isValidQuantity(item.goodsInfo, count)) {
		const validCount = spCart.adjustToValidQuantity(item.goodsInfo, count);
		item.count = validCount;
		ui.showToast(`该商品不支持拆零，已自动调整为${validCount}${item.goodsInfo.unit}`);
		count = validCount;
	}

	// 更新后端数量
	const success = await spCart.updateQuantity(item.id!, count);
	if (!success) {
		ui.showToast("更新数量失败");
	}
}

// 删除选中商品
async function toDel() {
	const selectedItems = spCart.list.filter((e) => e.checked);

	if (isEmpty(selectedItems)) {
		ui.showToast("请先选择商品");
	} else {
		ui.showConfirm({
			title: "提示",
			message: "确定删除选中商品吗？",
			async callback(action) {
				if (action == "confirm") {
					try {
						// 批量删除
						for (const item of selectedItems) {
							await spCart.del(item.id!);
						}
						// 刷新购物车列表
						await spCart.fetchCartList();
						// 刷新满减活动
						await spCart.fetchFullReductions();
						ui.showToast("删除成功");
						// 退出删除模式
						op.done();
					} catch (error) {
						console.error("删除商品失败:", error);
						ui.showToast("删除失败");
					}
				}
			},
		});
	}
}

// 去结算
async function toSettle() {
	// 防止重复点击
	if (op.settling) return;

	// 检查是否登录
	if (!user.token) {
		ui.showToast("请先登录");
		router.push("/pages/user/login");
		return;
	}

	const buyList = spCart.list.filter((e) => e.checked);

	if (isEmpty(buyList)) {
		ui.showToast("请先选择商品");
		return;
	}

	try {
		// 开始结算loading
		op.settling = true;

		const cartIds = buyList.map((item) => item.id!);
		// 如果有最优折扣，传递满减活动编号
		const mjBillNo = spCart.bestDiscount?.billNo;

		// 创建订单
		const result = await spCart.createOrderFromCart(cartIds, mjBillNo);
		ui.showToast("订单创建成功");
		router.push({
			path: "/pages/order/detail",
			params: {
				id: result.id,
			},
		});
	} catch (error: any) {
		console.error("创建订单失败:", error);
		ui.showToast(error.message || "订单创建失败");
	} finally {
		// 结束loading状态
		op.settling = false;
	}
}
</script>

<style lang="scss" scoped>
.shopping-cart-page {
	min-height: 100vh;
	background-color: #f7f8fa;
	display: flex;
	flex-direction: column;
}

// 自定义头部
.custom-header {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding-bottom: 20rpx;

	.header-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 32rpx;
		position: relative;

		.header-title {
			font-size: 36rpx;
			font-weight: 600;
			color: #ffffff;
		}

		.header-badge {
			position: absolute;
			left: 50%;
			transform: translateX(-50%);
			background: rgba(255, 255, 255, 0.2);
			padding: 4rpx 16rpx;
			border-radius: 20rpx;

			.badge-text {
				color: #ffffff;
				font-size: 24rpx;
			}
		}

		.header-action {
			.action-text {
				color: #ffffff;
				font-size: 30rpx;
				padding: 8rpx 16rpx;

				&:active {
					opacity: 0.7;
				}
			}
		}
	}
}

// 内容区域
.content-area {
	flex: 1;
	overflow-y: auto;
	padding-bottom: 120rpx;
}

// 促销横幅
.promotion-banner {
	margin: 20rpx 0;

	.promotion-scroll {
		height: 180rpx;
	}

	.promotion-container {
		display: flex;
		padding: 0 20rpx;
		gap: 16rpx;
	}

	.promotion-card {
		min-width: 320rpx;
		height: 160rpx;
		position: relative;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;

		&.active {
			box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.3);
			transform: scale(1.02);
		}

		.card-bg {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: linear-gradient(135deg, #ff6b6b 0%, #ffa502 100%);
			opacity: 0.9;
		}

		&.active .card-bg {
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		}

		.card-content {
			position: relative;
			z-index: 1;
			padding: 20rpx;
			display: flex;
			flex-direction: column;
			height: 100%;

			.card-header {
				display: flex;
				align-items: center;
				margin-bottom: 16rpx;

				.card-icon {
					width: 40rpx;
					height: 40rpx;
					background: rgba(255, 255, 255, 0.2);
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right: 12rpx;
				}

				.card-title {
					font-size: 26rpx;
					color: #ffffff;
					font-weight: 500;
				}
			}

			.card-rules {
				flex: 1;
				display: flex;
				flex-direction: column;
				gap: 8rpx;

				.rule-item {
					display: flex;
					align-items: center;
					gap: 8rpx;

					.rule-condition {
						font-size: 22rpx;
						color: rgba(255, 255, 255, 0.8);
					}

					.rule-discount {
						font-size: 28rpx;
						color: #ffffff;
						font-weight: 600;
					}
				}
			}

			.card-status {
				margin-top: 12rpx;

				.status-met,
				.status-need {
					display: flex;
					align-items: center;
					gap: 8rpx;
					font-size: 22rpx;
					color: #ffffff;
				}

				.status-met {
					background: rgba(16, 185, 129, 0.2);
					padding: 4rpx 12rpx;
					border-radius: 20rpx;
					width: fit-content;
				}
			}
		}
	}

	.discount-tip {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 16rpx;
		background: linear-gradient(90deg, #f0fdf4 0%, #e0f2fe 100%);
		margin: 16rpx 20rpx;
		border-radius: 12rpx;

		.tip-icon {
			margin-right: 8rpx;
		}

		.tip-text {
			font-size: 26rpx;
			color: #10b981;
			font-weight: 500;
		}
	}
}

// 购物车列表
.cart-list {
	padding: 0 20rpx;

	.list-container {
		background: #ffffff;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
	}

	.cart-group {
		.cart-item-wrapper {
			position: relative;

			&:not(.last-item)::after {
				content: "";
				position: absolute;
				bottom: 0;
				left: 20rpx;
				right: 20rpx;
				height: 1rpx;
				background: #f0f0f0;
			}

			.modern-cart-item {
				padding: 24rpx 20rpx;
				transition: background-color 0.2s ease;

				&:active {
					background-color: #f8f9fa;
				}
			}
		}
	}
}

// 空状态
.empty-state {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 40rpx;

	.empty-content {
		text-align: center;

		.empty-icon {
			margin-bottom: 40rpx;
		}

		.empty-title {
			font-size: 32rpx;
			color: #1a1a1a;
			font-weight: 500;
			margin-bottom: 16rpx;
			display: block;
		}

		.empty-desc {
			font-size: 26rpx;
			color: #999;
			margin-bottom: 60rpx;
			display: block;
		}

		.go-shopping-btn {
			padding: 20rpx 60rpx;
			font-size: 30rpx;
		}
	}
}

// 底部结算栏
.bottom-bar {
	position: fixed;
	bottom: 120rpx;
	left: 0;
	right: 0;
	background: #ffffff;
	box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);
	z-index: 100;

	.bar-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 32rpx;
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		.select-all {
			.custom-checkbox {
				:deep(.cl-checkbox__input) {
					margin-right: 12rpx;
				}

				.select-text {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}
			}
		}

		.price-info {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			gap: 20rpx;

			.price-detail {
				display: flex;
				flex-direction: column;
				align-items: flex-end;
				gap: 8rpx;

				.login-tip {
					font-size: 28rpx;
					color: #ff6b6b;
					font-weight: 500;
				}

				.original-price,
				.total-price {
					display: flex;
					align-items: baseline;
					gap: 8rpx;

					.price-label {
						font-size: 24rpx;
						color: #999;
					}

					.price-value {
						font-size: 32rpx;
						font-weight: 600;
						color: #ff4757;

						&.line-through {
							text-decoration: line-through;
							color: #999;
							font-size: 26rpx;
							font-weight: 400;
						}
					}
				}

				.total-price .price-value {
					font-size: 40rpx;
				}
			}

			.settle-btn {
				min-width: 200rpx;
				height: 80rpx;
				font-size: 30rpx;
				font-weight: 500;
				margin-left: 16rpx;

				.count-badge {
					font-size: 26rpx;
					margin-left: 8rpx;
				}
			}
		}

		.delete-action {
			flex: 1;
			display: flex;
			justify-content: flex-end;

			.delete-btn {
				padding: 16rpx 40rpx;
				height: 72rpx;
				font-size: 28rpx;

				&:disabled {
					opacity: 0.5;
				}
			}
		}
	}
}
</style>
